package code.view.menu {

import flash.events.KeyboardEvent;
import flash.system.Capabilities;

import mx.collections.ArrayCollection;
	

public class MenuItem {
	
	private var _label: String
	
	private var _fnCallback: Function;
	
	private var _children: ArrayCollection;
	
	private var _accelerator: Accelerator;
	
	private var _type: String;
	
	private static const _SEPARATOR: MenuItem = new MenuItem("", null, null, null, "separator");
	
	public var enabled: Boolean;
	
	
	public function MenuItem(label: String, fnCallback: Function, children: Array = null, acceleratorString: String = null, type: String = null, pEnabled: Boolean = true) {
		_label = label;
		_fnCallback = fnCallback;
		_children = children != null ? new ArrayCollection(children) : null;
		_accelerator = ((acceleratorString != null) ? Accelerator.fromString(acceleratorString) : null);
		_type = type;
		enabled = pEnabled;
	}
	
	public static function get SEPARATOR(): MenuItem {
		return _SEPARATOR;
	}
	
	public function toString(): String {
		return "MenuItem[label="+_label+";enabled="+enabled+"]";
	}
	
	public function get label(): String {
		return _label;
	}
	
	public function get children(): ArrayCollection {
		return _children;
	}
	
	public function get accelerator(): Accelerator {
		return _accelerator;
	}
	
	public function invokeCallback(): void {
		if(_fnCallback != null) {
			_fnCallback();
		}
	}
	
	public function isHandlingEvent(event: KeyboardEvent): Boolean {
		if(	_accelerator == null ||
			enabled == false) {
			return false;
		}
		
		if(Capabilities.os != "MacOS") {
    		return accelerator.test(event);
    	}
    	
    	// is mac os x
    	var keyCode: int = _accelerator.keyCodes[0];
        if(keyCode == 78) { // map nonmac.N to mac.N
        	keyCode = 14; // magic constant-hack for mac osx
        }
        return event.ctrlKey && event.keyCode == keyCode; 
	}
	
	public function get type(): String {
		return _type;
	}
}
}